package com.jk.util.io;

import com.jk.util.StringUtil;

import java.io.*;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by yanghuan on 2015/12/30.
 */
public class ZipUtil {

    public static void compressedFile(String resourcesPath, String targetPath, String targetName) throws IOException {
        File resourcesFile = new File(resourcesPath);     //源文件
        File targetFile = new File(targetPath);           //目的
        //如果目的路径不存在，则新建
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream outputStream;
        ZipOutputStream out = null;
        try {
            outputStream = new FileOutputStream(targetPath + File.separatorChar + targetName);
            out = new ZipOutputStream(new BufferedOutputStream(outputStream));
            createCompressedFile(out, resourcesFile, "");
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                out.close();
            }
        }
    }

    public static void createCompressedFile(ZipOutputStream out, File file, String dir) throws IOException {
        //如果当前的是文件夹，则进行进一步处理
        if (file.isDirectory()) {
            //得到文件列表信息
            File[] files = file.listFiles();
            //将文件夹添加到下一级打包目录
            if (!StringUtil.isEmpty(dir)) {
                dir = dir + File.separatorChar;
                out.putNextEntry(new ZipEntry(dir));
            }
            //循环将文件夹中的文件打包
            for (int i = 0; i < files.length; i++) {
                createCompressedFile(out, files[i], dir + files[i].getName());         //递归处理
            }
        } else {   //当前的是文件，打包处理
            //文件输入流
            FileInputStream fis = new FileInputStream(file);
            out.putNextEntry(new ZipEntry(dir));
            //进行写操作
            int j = 0;
            byte[] buffer = new byte[1024];
            while ((j = fis.read(buffer)) > 0) {
                out.write(buffer, 0, j);
            }
            //关闭输入流
            fis.close();
        }
    }
}
